import fs from "fs-extra";
import path from "path";
import YAML from 'yaml';
import { toolchain } from "../../toolchain.js";
import { BaseTask, TaskResult } from "./BastTask.js";
import { replaceInFile, replaceInFileOrThrow } from "../../tools/vendor.js";
import { YamlModifier } from "../../tools/YamlModifier.js";

/**
 * 设置脚本宏。
 */
export class SetImportFormatTask extends BaseTask {
    async run(): Promise<TaskResult<void>> {
        if (toolchain.option.engine == 'unity' && toolchain.option.platform == 'WebGL') {
            let format = toolchain.params.channelCfg.webgl?.textureImporterFormat;
            if (!format && toolchain.option.webglRuntime == 'douyin') {
                // 抖音默认为ASTC_8x8
                format = 'ASTC_8x8';

                // 修改默认的贴图压缩格式
                const ps = path.join(toolchain.params.workSpacePath, 'ProjectSettings/ProjectSettings.asset');
                const ym = new YamlModifier(ps, { indent: '  ' });
                const btdtcf = ym.modifier.getNodeOrThrow('PlayerSettings').getNodeOrThrow('m_BuildTargetDefaultTextureCompressionFormat');
                const nodes = btdtcf.getArraySubNodes();
                let contains = false;
                for (const node of nodes) {
                    if (node.getNodeOrThrow('m_BuildTarget').getValue() == 'WebGL') {
                        contains = true;
                        node.getNodeOrThrow('m_Format').setValue('3')
                    }
                }

                if (!contains) {
                    btdtcf.addArraySubNode({
                        m_BuildTarget: 'WebGL',
                        m_Format: '3'	
                    });
                }
                ym.save();
            }

            if (format) {
                const csf = path.join(toolchain.params.workSpacePath, 'Assets/Editor/AssetPostprocessorEx.cs');
                await replaceInFileOrThrow(csf, /static readonly TextureImporterFormat WebGLFormat = TextureImporterFormat\.\S+;/, `static readonly TextureImporterFormat WebGLFormat = TextureImporterFormat.${format};`);
            }
        }

        return { success: true, errorCode: 0 };
    }
}
